<script setup lang="ts">
import { Delete, Download, Plus } from '@element-plus/icons-vue';
import { DataViewInstance, fmtDate, hBtns, hStatusTag, openDialog, request, statusSelect, TableColumnProps } from '../../../utils';
import { onMounted, ref } from 'vue';

const columns = [
  { label: '岗位名称', prop: 'postName' },
  { label: '岗位编码', prop: 'postCode' },
  { label: '岗位排序', prop: 'postSort' },
  {
    label: '状态',
    render: (_, { row }) => hStatusTag(row.status)
  },
  {
    label: '创建时间',
    minWidth: 170,
    render: (h, { row }) => h('span', fmtDate(row.createAt))
  },
  {
    label: '操作',
    fixed: 'right',
    width: 120,
    render: (_, { row }) => {
      return hBtns([
        { label: '编辑', onClick: onEdit.bind(null, row) },
        { label: '删除', type: 'danger', onClick: onDelete.bind(null, [row]) }
      ])
    }
  }
] as TableColumnProps<any>[]

const fetchAction = (params: any): Promise<any> => request('/post/list', { params })

const onEdit = (row?: any) => {
  openDialog({
    vm: () => import('./edit.vue'),
    vmProps: { row },
    dialogProps: {
      title: row ? '编辑' : '新增',
      onSubmitted: () => tableRef.value?.getData()
    }
  })
}

const onDelete = (rows: any[]) => {
  tableRef.value?.deleteRows(
    () => request.post('/post/delete', { ids: rows.map(_ => _._id) })
  )
}

const tableRef = ref<DataViewInstance>()

onMounted(() => {
  tableRef.value?.getData()
})
</script>

<template>
  <UiDataView ref="tableRef" :fetch-action="fetchAction" :columns="columns" :config="{ selection: true, pager: false }">
    <template #form="{ form, onSearch }">
      <ElFormItem label="岗位编码">
        <ElInput placeholder="请输入岗位编码" v-model="form.postCode" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="岗位名称">
        <ElInput placeholder="请输入岗位名称" v-model="form.postName" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSelect placeholder="请选择状态" clearable v-model="form.status" @change="onSearch">
          <ElOption v-for="_ in statusSelect" :key="_.value" v-bind="_" />
        </ElSelect>
      </ElFormItem>
    </template>
    <template #actions="{ selectedRows }">
      <ElButton type="primary" plain :icon="Plus" @click="onEdit()">新增</ElButton>
      <ElButton type="danger" plain :icon="Delete" :disabled="selectedRows.length < 1" @click="onDelete(selectedRows)">删除</ElButton>
      <ElButton type="warning" plain :icon="Download">导出</ElButton>
    </template>
  </UiDataView>
</template>
